<template>
  <div>
    <div class="search-bar">
      <el-input
          class="custom-input"
          placeholder="请输入商品名称"
          v-model="searchKey"
          clearable>
      </el-input>
      <h3>总商品：{{goods.length}}</h3>
    </div>
    <div class="table-container">
      <table class="student-table">
        <thead>
        <tr class="sticky-header">
          <th>商品名称</th>
          <th>商品价格</th>
          <th>商品图片</th>
          <th>上架时间</th>
          <th>联系方式</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="g in filgoods" :key="g.id">
          <td>{{ g.goodsName }}</td>
          <td>{{ g.goodsPrice }}</td>
          <td>
            <img class="headimgurl" :src="g.goodsImgUrl" alt="Avatar" />
          </td>
          <td>{{ g.time }}</td>
          <td>{{g.number}}</td>
          <td><el-button
              type="danger"
              icon="el-icon-delete"
              circle
              class="delete-button"
              @click="deleteGoods(g.id)"></el-button></td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "SecondHand",
  data(){
    return {
      goods:[],
      searchKey:''
    }
  },
  mounted() {
    axios.post('/api/goods')
        .then(res =>{
          // console.log(res.data)
          this.goods = res.data.msg
        })
        .catch(err =>{
          alert(err)
        })
  },
  computed:{
    filgoods(){
      return this.goods.filter((item) =>{
        return item.goodsName.indexOf(this.searchKey) !== -1
      })
    }
  },
  methods:{
    deleteGoods(id){
      if (confirm('确定要删除该商品吗？')){
        axios.post(`/delect/api/goods/${id}`)
            .then(res =>{
              if (res.data.code === 0){
                alert('商品删除成功！')
                this.$router.go(0)
              } else {
                alert('商品删除失败！')
              }
            })
            .catch(err =>{
              alert(err)
            })
      }
    }
  }
}
</script>

<style scoped>
.custom-input {
  width: 100%; /* 输入框宽度自适应父容器宽度 */
  max-width: 500px; /* 设置输入框的最大宽度为 500 像素 */
}
.search-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  text-align: center;
}

.table-container {
  height: 550px; /* 设置表格容器的高度，根据实际情况调整 */
  overflow-y: scroll;
}
.sticky-header {
  position: sticky;
  top: 0;
  background-color: white;
}
.student-table {
  width: 100%;
  border-collapse: collapse;
}
.student-table tr:hover .delete-button {
  visibility: visible;
}
.delete-button {
  visibility: hidden;
}

.student-table th,
.student-table td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.student-table th {
  background-color: #f5f5f5;
}
.headimgurl{
  width: 50px;
  height: 50px;
  border-radius: 10px;
}
</style>